package com.example.cylooq.niceview.view

import android.Manifest
import com.example.cylooq.niceview.R
import com.example.cylooq.niceview.model.bean.VideoBean
import kotlinx.android.synthetic.main.activity_video_detail.*
import android.content.Context
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.Bitmap
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import com.bumptech.glide.Glide
import android.os.AsyncTask
import android.os.Handler
import android.os.Message
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.Toast
import com.example.cylooq.niceview.utils.*
import com.gyf.barlibrary.BarHide
import com.gyf.barlibrary.ImmersionBar
import com.shuyu.gsyvideoplayer.GSYVideoPlayer
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import zlc.season.rxdownload2.RxDownload
import java.io.FileInputStream
import java.io.FileNotFoundException


class VideoDetailActivity : AppCompatActivity() {
    companion object {
        var MSG_IMAGE_LOADED = 101
        var MSG_IMC_REFRASH = 100
    }

    lateinit var linearLayout: LinearLayout
    lateinit var imageView: ImageView
    lateinit var videoBean: VideoBean
    lateinit var orientationUtils: OrientationUtils
    var isPlay: Boolean = false
    var isPause: Boolean = false
    val activity: VideoDetailActivity = this
    var handle: Handler = object : Handler() {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            when (msg?.what) {
                MSG_IMAGE_LOADED -> {
                    //视频播放器设置封面
                    gsy_player_video_detail?.setThumbImageView(imageView)
                }
                MSG_IMC_REFRASH -> {
                    ImmersionBar.with(activity).transparentNavigationBar().statusBarAlpha(1f).fitsSystemWindows(true).init()
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_video_detail)
        videoBean = intent.getParcelableExtra("data")
        initView()
/*        ImmersionBar.with(this).transparentBar().barAlpha(0f).fitsSystemWindows(true).fullScreen(true)
                .statusBarView(views).hideBar(BarHide.FLAG_HIDE_STATUS_BAR) .init()*/
        ImmersionBar.with(activity).transparentNavigationBar().statusBarAlpha(1f).fitsSystemWindows(true).init()
        initPlayVideo()
    }

    private fun initView() {
        val urli=SharedPreferenceUtils.getInstance(this,"historys").getString(videoBean?.playUrl!!)
        if(urli.equals("")){
            var count = SharedPreferenceUtils.getInstance(this,"historys").getInt("count")
            if(count!=-1){
                count = count.inc()
            }else{
                count = 1
            }
            SharedPreferenceUtils.getInstance(this,"historys").put("count",count)
            SharedPreferenceUtils.getInstance(this,"historys").put(videoBean?.playUrl!!,videoBean?.playUrl!!)
            ObjectSaveUtils.saveObject(this,"history$count",videoBean)
        }
        var bgUrl = videoBean?.blurred
        linearLayout = findViewById(R.id.video_detail)
        SetBackgroundViewAsyncTask(handle, this, linearLayout).execute(bgUrl)
        video_title_detail.text = videoBean?.title
        video_time_detail.text = videoBean?.title
        video_desc_detail.text = videoBean?.description
        var category = videoBean?.category
        var duration = videoBean?.duration
        var minute = duration?.div(60)
        var second = duration?.minus((minute?.times(60)) as Long)
        var realMinute: String
        var realSecond: String
        if (minute!! < 10) {
            realMinute = "0" + minute
        } else {
            realMinute = minute.toString()
        }
        if (second!! < 10) {
            realSecond = "0" + second
        } else {
            realSecond = second.toString()
        }
        video_time_detail.text = "$category / $realMinute'$realSecond''"
        share_num_detail.text = videoBean?.share?.toString()
        favorite_num_detail.text = videoBean?.collect?.toString()
        comment_num_detail.text = videoBean?.share?.toString()
        icon_download_detail.setOnClickListener {
            //点击下载按钮
            val url = videoBean.playUrl
                    ?.let { it1 ->
                        SharedPreferenceUtils
                                .getInstance(this, "downloads").getString(it1)
                    }
            if (url.equals("")) {
                var count = SharedPreferenceUtils.getInstance(this, "downloads")
                        .getInt("count")
                if (count != -1){
                    count=count.inc()
                }else{
                    count=1
                }
                SharedPreferenceUtils.getInstance(this,"downloads").put("count",count)
                ObjectSaveUtils.saveObject(this,"download$count",videoBean)
                addDownload(videoBean?.playUrl,count)
            } else {
                ToastMine(this, "已经缓存过该视频了", Toast.LENGTH_SHORT)
            }
        }
    }

    private fun addDownload(playUrl: String?, count: Int) {
        RxDownload.getInstance(activity).serviceDownload(playUrl,"download$count")
                .subscribe({
                    ToastMine(activity,"开始下载",Toast.LENGTH_SHORT)
                    SharedPreferenceUtils.getInstance(this,"downloads")
                            .put(videoBean.playUrl.toString(),videoBean.playUrl.toString())
                    SharedPreferenceUtils.getInstance(this,"download_state")
                            .put(videoBean.playUrl.toString(),true)
                },{
                    ToastMine(this,"添加下载任务失败",Toast.LENGTH_SHORT)
                })
    }

    private fun initPlayVideo() {
        var playUrl: String? = intent?.getStringExtra("localFile") ?: null
        if (playUrl != null) {
            gsy_player_video_detail.setUp(playUrl, false, null, null)
        } else {
            playUrl = videoBean?.playUrl
            gsy_player_video_detail.setUp(playUrl, false, null, null)
        }
        //添加视频封面
        imageView = ImageView(this)
        imageView.scaleType = ImageView.ScaleType.CENTER_CROP
        SetImageViewAsyncTask(handle, this, imageView).execute(videoBean?.feed)
        orientationUtils = OrientationUtils(this, gsy_player_video_detail)
        gsy_player_video_detail.setIsTouchWiget(true)
        //不自动旋转
        gsy_player_video_detail.isRotateViewAuto = false
        gsy_player_video_detail.isNeedLockFull = true
        gsy_player_video_detail.isLockLand = false
        gsy_player_video_detail.isShowFullAnimation = false
        //设置标题栏隐藏
        gsy_player_video_detail.titleTextView.visibility = View.GONE

        gsy_player_video_detail.fullscreenButton.setOnClickListener {
            //直接横屏，再全屏观看视频
            ImmersionBar.with(activity).reset().init()
            orientationUtils.resolveByClick()

            //ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_BAR).init()
            gsy_player_video_detail.startWindowFullscreen(this, true, true)
        }
        gsy_player_video_detail.setStandardVideoAllCallBack(object : VideoListener() {
            override fun onPrepared(url: String?, vararg objects: Any?) {
                super.onPrepared(url, *objects)
                //开始播放了才能旋转和全屏
                orientationUtils.isEnable = true
                isPlay = true

            }

            override fun onAutoComplete(url: String?, vararg objects: Any?) {
                super.onAutoComplete(url, *objects)
            }

            override fun onClickStartError(url: String?, vararg objects: Any?) {
                super.onClickStartError(url, *objects)
            }

            override fun onQuitFullscreen(url: String?, vararg objects: Any?) {
                super.onQuitFullscreen(url, *objects)
                ImcSsyncTask(handle, activity)
                orientationUtils?.let { orientationUtils.backToProtVideo() }
            }
        })
        gsy_player_video_detail.setLockClickListener {
            //配合下方的onConfigurationChanged
            view, lock ->
            orientationUtils.isEnable = !lock
        }
        gsy_player_video_detail.setOnClickListener(View.OnClickListener {
            onBackPressed()
        }
        )
        //设置返回按钮可见
        gsy_player_video_detail.backButton.visibility = View.VISIBLE
        gsy_player_video_detail.backButton.setOnClickListener({
            //设置返回按钮
            onBackPressed()
        })

    }

    override fun onBackPressed() {
        orientationUtils?.let {
            orientationUtils.backToProtVideo()
        }
        if (StandardGSYVideoPlayer.backFromWindowFull(this)) {
            ImcSsyncTask(handle, activity)
            return
        }
        super.onBackPressed()
    }


    override fun onPause() {
        super.onPause()
        isPause = true
    }

    override fun onResume() {
        super.onResume()
        isPlay = true
    }

    override fun onDestroy() {
        super.onDestroy()
        //释放所有视频资源
        GSYVideoPlayer.releaseAllVideos()
        orientationUtils?.let { orientationUtils.releaseListener() }
    }

    //AsyncTask异步线程
    private class ImcSsyncTask(handler: Handler, activity: VideoDetailActivity) : AsyncTask<String, Void, String>() {
        private var handlerAsync: Handler = handler
        override fun doInBackground(vararg p0: String?): String {
            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        }

        override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            var msg = handlerAsync.obtainMessage()
            msg.what = MSG_IMC_REFRASH
            handlerAsync?.sendMessage(msg)
        }
    }

    private class SetImageViewAsyncTask(handler: Handler, activity: VideoDetailActivity, private val imageViewAsync: ImageView) : AsyncTask<String, Void, String>() {
        private var handlerAsync: Handler = handler
        private var path: String? = null
        private var fileInputStream: FileInputStream? = null
        private var mainActivity: VideoDetailActivity = activity
        override fun doInBackground(vararg params: String?): String? {
            try {
                val glideLoad = Glide.with(mainActivity)
                        .load(params[0])
                        .downloadOnly(100, 100)
                try {
                    var catchFile = glideLoad.get()
                    path = catchFile.absolutePath
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return path
        }

        override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            try {
                fileInputStream = FileInputStream(result)
            } catch (e: Exception) {
                e.printStackTrace()
            }
            val bitMap = BitmapFactory.decodeStream(fileInputStream)
            imageViewAsync.setImageBitmap(bitMap)
            var msg = handlerAsync.obtainMessage()
            msg.what = MSG_IMAGE_LOADED
            handlerAsync?.sendMessage(msg)
        }
    }

    private class SetBackgroundViewAsyncTask(handler: Handler, activity: VideoDetailActivity, private val linearLayouts: LinearLayout) : AsyncTask<String, Void, String>() {
        private var path: String? = null
        private var fileInputStream: FileInputStream? = null
        private var drawable: Drawable? = null
        private var mainActivity: VideoDetailActivity = activity
        override fun doInBackground(vararg params: String?): String? {
            try {
                val glideLoad = Glide.with(mainActivity)
                        .load(params[0])
                        .downloadOnly(100, 100)
                try {
                    var catchFile = glideLoad.get()
                    path = catchFile.absolutePath
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return path
        }

        override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            try {
                fileInputStream = FileInputStream(result)
            } catch (e: Exception) {
                e.printStackTrace()
            }
            drawable = Drawable.createFromStream(fileInputStream, null)
            linearLayouts?.background = drawable
        }
    }

    //重写配置改变时操作
    override fun onConfigurationChanged(newConfig: Configuration?) {
        super.onConfigurationChanged(newConfig)
        if (isPlay && !isPause) {
            if (newConfig?.orientation == ActivityInfo.SCREEN_ORIENTATION_USER) {
                if (!gsy_player_video_detail.isIfCurrentIsFullscreen) {
                    gsy_player_video_detail.startWindowFullscreen(this, true, true)
                }
            } else {
                if (gsy_player_video_detail.isIfCurrentIsFullscreen) {
                    StandardGSYVideoPlayer.backFromWindowFull(this)
                }
                orientationUtils?.let { orientationUtils.isEnable = true }
            }
        }
    }

}
